package com.zhanghp.class034;


import com.zhanghp.common.ListNode;

/**
 * 返回链表的第一个入环节点<br/>
 * 测试链接 : https://leetcode.cn/problems/linked-list-cycle-ii/<br/>
 *
 * @author zhanghp
 * @since 2024/4/11 9:56
 */
public class Code05_LinkedListCyclell {

    static class Solution {
        public ListNode detectCycle(ListNode head) {
            if (head == null || head.next == null || head.next.next == null) {
                return null;
            }
            ListNode slow = head.next, fast = head.next.next;
            // 环
            // 先找环内相交后的点
            while (slow != fast) {
                if (fast.next == null || fast.next.next == null) {
                    return null;
                }
                slow = slow.next;
                fast = fast.next.next;
            }
            // 第一个交点
            // 从head从头往下找，和slow碰见（指定能碰到，左神:记结论）
            fast = head;
            while (fast != slow) {
                fast = fast.next;
                slow = slow.next;
            }
            return slow;
        }
    }
}
